package com.glsc.ngateway.opmanage.service.report.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.glsc.ngateway.common.base.domain.postgre6.GtjaIRS;
import com.glsc.ngateway.common.base.repo.postgre6.GtjaIRSRepo;
import com.glsc.ngateway.common.base.utils.ExcelDoubleConverter;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GtjaIRSListener extends AnalysisEventListener<Map<Integer, String>> {
    private static final int BATCH_COUNT = 3000;
    List<GtjaIRS> list = new ArrayList<>();

    private GtjaIRSRepo gtjaIRSRepo;
    private String ywyf;
    private Boolean clearFlag = false;

    public String getYwyf() {
        return ywyf;
    }

    public GtjaIRSListener() {
    }

    public GtjaIRSListener(GtjaIRSRepo gtjaIRSRepo) {
        this.gtjaIRSRepo = gtjaIRSRepo;
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        ReadRowHolder readRowHolder = context.readRowHolder();
        Integer rowIndex = readRowHolder.getRowIndex();
        Map<Integer, Cell> dataMap = readRowHolder.getCellMap();

        if (rowIndex == 2) {
            ywyf = data.get(1);
        } else if (rowIndex >= 6 && StringUtils.hasLength(data.get(1))) {
            list.add(new GtjaIRS(
                    ywyf,
                    data.get(0),
                    data.get(1),
                    data.get(2),
                    ExcelDoubleConverter.cellToDouble(dataMap, 3),
                    data.get(4),
                    data.get(5),
                    data.get(6),
                    data.get(7),
                    data.get(8),
                    data.get(9),
                    data.get(10),
                    ExcelDoubleConverter.cellToDouble(dataMap, 11)
            ));
        }

        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        if (!clearFlag) {
            clearFlag = true;
            gtjaIRSRepo.delete(ywyf);
        }
        gtjaIRSRepo.saveAll(list);
    }
}
